'''
批量获取给定目录下文件的MD5值
'''

import hashlib
import sys, os, re
 
def calculate_md5(filepath):
    with open(filepath, 'rb') as file:
        md5 = hashlib.md5()
        while True:
            data = file.read(4096)
            if not data:
                break
            md5.update(data)
    
    return md5.hexdigest()

def parse_argv(arg):
    if arg in sys.argv:
        return sys.argv[sys.argv.index(arg)+1]

def OSis_hidden(path):
    '''
        是否为隐藏文件
    '''
    if os.path.basename(path).startswith("~$") or os.path.basename(path).startswith("$") or os.path.basename(path).startswith("~") or os.path.basename(path).startswith("."):
        return True
    else:
        return False


def argv_files(index=1):
    """
        根据sys.argv指定位置index的路径字符串
        如果路径是文件则直接返回；如果是文件夹则遍厉该路径下所有文件并返回
    """
    if len(sys.argv)>index:
        path = parse_argv('-f')
        if not path:
            path = sys.argv[index]
        if not os.path.exists(path):
            print(f"路径{path}不存在")
        else:
            if os.path.isfile(path):
                yield path
            else:
                for cur, dirs, files in os.walk(path):
                    for file in files:
                        yield os.path.join(cur, file)

if __name__=="__main__":
    path = sys.argv[1]
    # if os.path.isfile(path):
    #     print(f"file:{path}的MD5是：")
    #     print(calculate_md5(path))
    # else:
    for path in argv_files():
        if '--all' not in sys.argv:
            ext = [".zip", '.rar']
            # if path.endswith(".zip"): 
            for e in ext:
                if re.search(f'{e}$', path, flags=re.I):
                    print(f"file:{path}的MD5是：")
                    print(calculate_md5(path))
        elif not OSis_hidden(path):
            print(f"file:{path}的MD5是：")
            print(calculate_md5(path))
